package com.demo.springcloud.controller;

import com.demo.springcloud.pojo.CommonResult;
import com.demo.springcloud.pojo.Payment;
import com.demo.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chenyuan
 * @date 2020/11/30 18:17
 */
@Slf4j
@RestController
@RequestMapping("/provider")
public class PaymentController {
	@Autowired
	private PaymentService paymentService;

	@Value("${server.port}")
	private String serverPort;

	/**
	 * 注入 服务发现
	 */
	@Autowired
	private DiscoveryClient discoveryClient;

	/**
	 * 暴露查询自己相关信息的接口
	 */
	@GetMapping(value = "/payment/discovery")
	public Object discovery() {
		// 获取服务列表清单
		List<String> services = discoveryClient.getServices();
		for (String element : services) {
			log.info("***** element:" + element);
		}
		// 获得指定的微服务名称对应的实例
		List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
		for (ServiceInstance instance : instances) {
			log.info("ServiceId : " + instance.getServiceId() + "\n" +
					"Host : " + instance.getHost() + "\n" +
					"Port :" + instance.getPort() + "\n" +
					"Uri : " + instance.getUri());
		}
		return this.discoveryClient;
	}

	@GetMapping("/getPaymentById/{id}")
	public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
		Payment payment = paymentService.getById(id);
		log.info("[=查询结果=]{" + payment + "}");
		if (payment != null) {
			return new CommonResult<>(200, "【端口：】" + serverPort + "---【查询成功】", payment);
		} else {
			return new CommonResult<>(444, "【查询失败】");
		}
	}

	@PostMapping("/addPayment")
	public CommonResult<Payment> addPayment(@RequestBody Payment payment) {
		log.info("[=插入数据=]{" + payment + "}");
		int insert = paymentService.insert(payment);
		if (insert != 0) {
			return new CommonResult<>(200, "【插入成功】", payment);
		} else {
			return new CommonResult<>(444, "【插入失败】");
		}
	}

	/**
	 * 用于测试自定义负载均衡
	 */
	@GetMapping(value = "/payment/lb")
	public String getPaymentLB() {
		return serverPort;
	}

	/**
	 * zipkin
	 */
	@GetMapping("/payment/zipkin")
	public String paymentZipkin() {
		return "hi ,i'am paymentzipkin server fall back，O(∩_∩)O哈哈~";
	}


}
